package com.sh4.service.impl;


import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sh4.dao.impl.WxUserDaoImpl;
import com.sh4.entity.WxUser;
import com.sh4.wxservice.User;
import com.sh4.wxservice.WeChatRequest;

import net.sf.json.JSONObject;

/**
 * 服务号 业务层
 *
 * @author taotao
 *
 */
@Service("coreServiceImpl")
@Transactional
public class CoreServiceImpl {

	@Autowired
	private WxUserDaoImpl wxUserDaoImpl;

	/**
	 * 普通关注事件 （直接 搜索）
	 */
	public  String subscribe(WeChatRequest requestMap) {

		String respContent = null;
		respContent = this.subSaveAndSend(requestMap.getFromUserName(), requestMap.getCreateTime(), null,
				requestMap.getCompanyToken(), requestMap);

		return respContent;
	}

	/**
	 * 取消订阅（关注）
	 */
	public  void unSubscribe(String openId) {
		// BaseService baseService = ContextHolder.getBean("baseService");
		// try {
		//
		// String hql = "from CrmCustomer where openId = ?";
		// CrmCustomer rs = baseService.findObject(hql, openId);
		// if (rs != null) {
		// rs.setAttentionStatus("0");
		// rs.setUpdatedDate(new Date());
		// rs.setUpdateBy(openId);
		// baseService.saveOrUpdate(rs);
		// // 推送
		// }
		// } catch (Exception e) {
		// }
	}

	/**
	 * 扫码关注事件 （生成 新的会员,并通知）
	 */
	public  String subscribeScan(WeChatRequest requestMap) {
		String respContent = this.subSaveAndSend(requestMap.getFromUserName(), requestMap.getCreateTime(),
				requestMap.getEventKey().substring(8), requestMap.getCompanyToken(), requestMap);// 户未关注时，进行关注后的事件
																									// 二维码参数
		// 前缀qrscene_
		return respContent;
	}

	/**
	 * 已关注扫码事件
	 *
	 * @param requestMap
	 * @return
	 */
	@SuppressWarnings("unused")
	public  String subscribeOldScan(WeChatRequest requestMap) {

		String eventKey = requestMap.getEventKey();

		return this.subSaveAndSend(requestMap.getFromUserName(), requestMap.getCreateTime(), eventKey,
				requestMap.getCompanyToken(), requestMap);
	}

	/**
	 * 关注 生成会员 且消息推送 公用方法
	 * 
	 * @param openId
	 * @param createTime
	 * @param qrCode
	 * @param token
	 * @param requestMap
	 * @param ruleCode
	 * @return
	 */
	public  String subSaveAndSend(String openId, Long createTime, String ruleCode, String token,
			WeChatRequest requestMap) {
		String respContent = null, customerCode = null;
		try {

			/**
			 * 获取用户微信信息 并更新 微信表
			 */
			System.out.println("JSON：==》  start");
			WxUser userInfo = User.userInfo(openId, "zh_CN", token);
			System.out.println("JSON：==》 " + JSONObject.fromObject(userInfo).toString());
			if (userInfo != null) {
				System.out.println("JSON：==》  111");
				if (StringUtils.isNotBlank(userInfo.getOpenid())) {
//					
//					WxUser user = (WxUser) coreServiceImpl.wxUserDaoImpl.getUniqueResult("from WxUser u where u.openid = ?", userInfo.getOpenid());
//					if(user == null) {
////						coreServiceImpl.wxUserServiceImpl.save(userInfo);
//						coreServiceImpl.wxUserDaoImpl.add(userInfo);
//						System.out.println("save");
//					}else {
//						userInfo.setCompanyId(requestMap.getCompanyCode());
////						coreServiceImpl.wxUserServiceImpl.saveOrUpdate(userInfo);
//						
//						System.out.println("saveOrUpdate");
//					}
					wxUserDaoImpl.saveOrUpdate(userInfo);
					System.out.println("JSON：==》  end");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respContent;

	}

	public  void test() {
		WxUser userInfo = new WxUser();
		
		userInfo.setOpenid("eeeeeedsdsds");
//		
//		WxUser user = (WxUser) coreServiceImpl.wxUserDaoImpl.getUniqueResult("from WxUser u where u.openid = ?", userInfo.getOpenid());
//		if(user == null) {
////			coreServiceImpl.wxUserServiceImpl.save(userInfo);
//			coreServiceImpl.wxUserDaoImpl.add(userInfo);
//			System.out.println("save");
//		}else {
////			userInfo.setCompanyId(requestMap.getCompanyCode());
////			coreServiceImpl.wxUserServiceImpl.saveOrUpdate(userInfo);
//			coreServiceImpl.wxUserDaoImpl.saveOrUpdate(userInfo);
//			System.out.println("saveOrUpdate");
//		}
//		System.out.println("JSON：==》  end");
		wxUserDaoImpl.saveOrUpdate(userInfo);
	}
	
	public void save(WxUser user) {
		
		wxUserDaoImpl.saveOrUpdate(user);
		
	}

	/**
	 * 推消息
	 * 
	 * @param vip
	 * @param requestMap
	 */
	// public  void sentMess(CrmCustomer vip,WeChatRequest requestMap) {
	// CrmCompanyWxInfo wx =
	// CompanyWeChatCache.companyWXInfo.get(requestMap.getCompanyCode());
	// /**
	// * 推送欢迎关注 图文消息
	// */
	// ClientService.SNewsMsg(requestMap.getFromUserName(), "欢迎关注" +
	// wx.getCompanyDesc(), "欢迎关注" + wx.getCompanyDesc() + "\n注册会员享有更多服务哦
	// \n点击查看全文，进行身份验证吧！"
	// , wx.getAttribute4()
	// , wx.getCompanyLogo(),
	// CompanyWeChatCache.getServeToken(requestMap.getCompanyCode()));
	//// ClientService.SNewsMsg(requestMap.getFromUserName(), "欢迎加入" +
	// requestMap.getCompanyCode() + "会员俱乐部",
	//// "欢迎加入" + requestMap.getCompanyCode() + "会员大家族！\n您的会员编号为：" +
	// vip.getCustomerCode() + "\n点击查看全文，进行身份验证吧！"
	//// ,Configure.getString("guanZhuUrl")+"mobile/recruitMember/info?state="+requestMap.getCompanyCode()+"&url="+Configure.getString("guanZhuUrl")+"myStore/assets/html/members/authentication.html",
	//// wx.getCompanyLogo());
	//
	//// /**
	//// * 给门店推送关注提醒
	//// */
	//// SMessage.SNewsMsg(qyUtil.WECHAT, qyUtil.remindId, "新粉丝关注提醒!",
	//// "有新的粉丝加入" + KMTUtil.companyName + "会员俱乐部！\n 昵称：" + nickname + "\n 性别："
	//// + (Integer.parseInt(sex) == 1 ? '男' : '女') + "\n 会员编号 :" + customer,
	//// "", headimgurl);
	//
	// }
}
